<template>
  <div class="container">
    <chgpwd-detail></chgpwd-detail>
    <my-sign-in :try-sign-in="trySignIn"></my-sign-in>
    <my-language-select :language.once="language"></my-language-select>
  </div>
</template>

<script>
import Vue from 'vue'
import ebus from 'libs/ebus.js'
import {http} from 'share/server/api.js'
import toast from 'libs/toast.js'
import {encryptPassword} from 'share/server/utils.js'
import {getPlatformInfo, tryLogin, setLanguage} from 'share/server/vuex/actions/system.js'
import {userRoleCfg} from '../configs/userRoleCfg.js'
import ChgpwdDetail from './ChgpwdDetail.vue'

export default {
  components: {
    'chgpwd-detail': ChgpwdDetail
  },
  data () {
    return {
      language: Vue.config.lang
    }
  },
  vuex: {
    getters: {
      client: (state) => state.auth.client
    },
    actions: {
      getPlatformInfo,
      tryLogin,
      setLanguage
    }
  },
  methods: {
    signIn () {
      var router = this.$router
      var url = '/'

      if (this.client.role && userRoleCfg[this.client.role]) {
        let cfg = userRoleCfg[this.client.role]
        url = cfg.dftUrl
      }
      router.go(url)
    },
    encryptPassword (plaintext) {
      //兼容旧版本，待废弃
      if (plaintext === 'admin') {
        return plaintext
      } else {
        return encryptPassword(plaintext)
      }   
    },
    trySignIn (verify) {
      let ctx = this
      let req = {
        username: verify.username,
        password: this.encryptPassword(verify.password),
        code: ''
      }

      http('/api/auth/logout', 'POST').then(function(res) {
        this.tryLogin(req, {
          success: this.signIn,
          error (data) {
            toast.code(ctx, data)
          },
          noResponse () {
            toast.e(ctx, ctx.$t('common.fail'), ctx.$t('error.noResponse'))
          }
        })
      }.bind(this), function(res) {
        toast.e(ctx, ctx.$t('common.fail'), ctx.$t('error.noResponse'))
      })
    },
    onChangeLang (lang) {
      Vue.config.lang = lang
      this.setLanguage(lang)
    }
  },
  ready: function() {
    this.getPlatformInfo()
    this.setLanguage(this.language)
    ebus.on('change-language', this.onChangeLang)
  }
}
</script>

<style scoped>
.container {
  padding-top: 40px;
  padding-bottom: 40px;
}
</style>